import Vue from 'vue'
import Vuex from 'vuex'
import $http from './ajax'
import Toast from 'muse-ui-toast'

Toast.config({position: 'top', time: 1800});

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    showNav: true, // 是不是显示底部导航
    defaultHeader: true, // 显示默认的header
    user: {
      houseNo: '',
      roomNo: '',
      name: '',
      tel: '',
      qq: '',
      password: '',
      password2: ''
    },
    cost: { // 主页的费用
      power: 10,
      airConditioner: 20
    },
    searchRepairKey: '', // 广场的搜索关键字
    nav: 'home', // 当前的底部导航位置
    openLogin: false, // 打开登录弹窗
    token: '', // 登录状态 暂时保存这样子
    myAdvises: [], // 我的建议
    myRepairs: [], // 我的报修记录
    sysNotices: [], // 系统公告
    allRepairs: [] // 维修广场
  },
  mutations: {
    showHeader(state, val) {
      state.defaultHeader = val
    },
    showNav(state, val) {
      state.showNav = val
    },
    setSearchRepairKey(state, val) {
      state.searchRepairKey = val
    },
    updateNav(state, val) {
      state.nav = val
    },
    updateOpenLogin(state, val) {
      state.openLogin = val
    },
    setToken(state, token) {
      state.token = token
    },
    setUser(state, user) {
      this.commit('setToken', user.token);
      delete user.token;
      delete user.password;
      delete user.username;
      state.user = {...user, password: '', password2: ''}
    },
    clearUser(state) {
      state.user = {houseNo: '', roomNo: '', name: '', tel: '', qq: '', password: '', password2: ''};
      state.token = ''
    },
    updateNotice(state, ns) {
      state.sysNotices = ns;
    }
  },
  actions: {
    loadAdvise ({commit, state}, page) {
      return $http.post('/api/advise/self', {page: page, limit: 10}).then(data => {
        if (data.success) {
          let rs = data.payload.records;
          if (page === 1) {
            state.myAdvises = rs
          } else {
            state.myAdvises = [...state.myAdvises, ...rs]
          }
        }
      })
    },
    loadAllRepair ({commit, state}, page) {
      return $http.post('/api/repair/page', {page: page, limit: 10}).then(data => {
        if (data.success) {
          let rs = data.payload.records;
          if (page === 1) {
            state.allRepairs = rs
          } else {
            state.allRepairs = [...state.allRepairs, ...rs]
          }
        }
      })
    },
    loadRepair ({commit, state}, page) {
      return $http.post('/api/repair/self', {page: page, limit: 10}).then(data => {
        if (data.success) {
          let rs = data.payload.records;
          if (page === 1) {
            state.myRepairs = rs
          } else {
            state.myRepairs = [...state.myRepairs, ...rs]
          }
        }
      })
    },
    //// 公告加载
    loadNotice ({commit, state}, page) {
      return $http.post('/api/notices', {page: page}, false).then(data => {
        if (data.success) {
          if (page === 1) {
            state.sysNotices = data.payload.records
          } else {
            state.sysNotices = [...state.sysNotices, ...data.payload.records]
          }
        }
      })
    },
    initApp({commit, state}, vm) {
      // if (state.token === '') {
      //   commit('updateNeedLogin', true)
      // }
      this.dispatch('checkSession');
      this.dispatch('loadNotice', 1)
    },
    doLogin({commit}, info) {
      $http.post('/api/login', info, false).then(data => {
        if (data.success) {
          Toast.success("登录成功！");
          this.dispatch('updateSession', data.payload);
          commit('setUser', data.payload);
          commit('updateOpenLogin', false)
        } else {
          Toast.error("登录失败：" + data.msg)
        }
      });
    },
    doLogout({commit}) {
      commit('clearUser');
      sessionStorage.setItem("app_token", '');
      Toast.success("注销成功！")
    },
    authLogin ({commit, state}) {
      this.dispatch('checkSession');
      if (state.token == null || state.token === '') {
        commit('updateOpenLogin', true);
        return false
      } else {
        return true
      }
    },
    checkSession ({commit}) {
      let us = sessionStorage.getItem("app_token");
      if (us != null && us !== '' && us.length > 10) {
        commit('setUser', JSON.parse(us))
      }
    },
    updateSession ({commit}, user) {
      var oldu = {};
      var us = sessionStorage.getItem("app_token");
      if (us != null && us !== '' && us.length > 10) {
        oldu = JSON.parse(us)
      }
      sessionStorage.setItem("app_token", JSON.stringify(Object.assign(oldu, user)))
    }
  }
})
